package net.ufrog.common.spring.app;

import net.ufrog.common.Logger;
import net.ufrog.common.web.app.WebApp;
import net.ufrog.common.web.app.WebAppFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ultrafrog
 * @version 0.1, 2014-01-19
 * @since 0.1
 */
public class SpringWebAppFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        Logger.info("initialize spring web application filter");
        SpringWebApp.initialize(config.getServletContext());
        Logger.info("spring web application filter is running...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        if (!WebApp.resource(req)) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) req;
            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
            req.setAttribute(WebAppFilter.PARAM_KEY, SpringWebApp.create(httpServletRequest, httpServletResponse));
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        Logger.info("destroyed spring application filter!");
    }
}
